<template>
  <div style="width: 100%; margin-left: 10px">
    <titleNav></titleNav>
    <div style="margin-top: 10px; display: flex">
      订单号：<el-input
        v-model="pageName.repairId"
        placeholder="请输入订单号"
        style="width: 15%"
      ></el-input>
      &nbsp; 联系人：<el-input
        v-model="pageName.contactName"
        placeholder="请输入联系人"
        style="width: 15%"
      ></el-input>
      &nbsp; 受理人：<el-input
        v-model="pageName.acceptorName"
        placeholder="请输入受理人"
        style="width: 15%"
      ></el-input>
      &nbsp;
      <div style="width: 35%; display: flex">
        <p>选择时间范围</p>

        <el-date-picker
          v-model="value1"
          type="datetimerange"
          range-separator="到"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
        />
        &nbsp;
        <el-button @click="getList1">查询</el-button>
      </div>
    </div>
    <!-- 控制订单状态 -->
    <el-radio-group
      v-model="radio1"
      size="large"
      style="margin-top: 10px"
      @change="getList"
    >
      <el-radio-button label="未审核订单" value="CREATE" />
      <el-radio-button label="通过审核订单" value="APPROVED" />
      <el-radio-button label="未通过审核订单" value="REJECTED" />
      <el-radio-button label="待受理订单" value="PENDING" />
      <el-radio-button label="维修中" value="REPAIR" />
    </el-radio-group>

    <el-table
      :data="pagedTableData"
      :table-layout="tableLayout"
      border
      style="width: 100%; margin-top: 10px"
    >
      <!-- <el-table-column prop="deptName" label="所属部门" width="100" />
      <el-table-column prop="repairId" label="订单编号" width="180" />
      <el-table-column prop="createTime" label="创建时间" width="280" />
      <el-table-column prop="contactName" label="联系人" width="100" />
      <el-table-column prop="contactPhone" label="联系方式" width="180" />
      <el-table-column prop="equipmentList" label="报修设备" width="180" />
      <el-table-column prop="faultDescription" label="报修原因" width="280" />
      <el-table-column prop="faultAddress" label="所在地区" width="200" /> -->
      <el-table-column
        v-for="item in headers"
        :key="item.prop"
        :prop="item.prop"
        :label="item.label"
        width="180"
      ></el-table-column>

      <el-table-column prop="repairStatus" label="订单状态" align="center">
        <template #default="scope">
          <span v-if="scope.row.repairStatus === 'CREATE'">未审核</span>
          <span v-else-if="scope.row.repairStatus === 'APPROVED'">通过</span>
          <span v-else-if="scope.row.repairStatus === 'REJECTED'">拒绝</span>
          <span v-else-if="scope.row.repairStatus === 'PENDING'">待受理</span>
          <span v-else-if="scope.row.repairStatus === 'REPAIR'">维修中</span>
          <span v-else-if="scope.row.repairStatus === 'ACCEPTED'"
            >验收通过</span
          >
        </template>
      </el-table-column>

      <el-table-column fixed="right" label="操作" width="180" align="center">
        <template #default="scope">
          <div v-if="radio1 == 'APPROVED'">
            <el-button
              type="primary"
              style="text-align: center"
              size="small"
              @click="Dispatch(scope.row)"
              >派单</el-button
            >
          </div>
          <div v-else-if="radio1 == 'CREATE'">
            <ConfirmDialog
              @confirm="aggree(scope.row)"
              @cancel="onCancel"
              ref="confirmDialog"
            />
            <el-button
              type="primary"
              icon="el-icon-edit"
              style="width: 50px; text-align: center"
              size="small"
              @click="openConfirmDialog"
              >同意</el-button
            >
            <el-button
              type="danger"
              style="width: 50px; text-align: center"
              size="small"
              @click="rejuct(scope.row)"
              >拒绝</el-button
            >
          </div>
          <div v-else-if="radio1 == 'PENDING'">
            <el-button
              type="primary"
              icon="el-icon-edit"
              style="width: 50px; text-align: center"
              size="small"
              @click="PutreciveOrder(scope.row)"
              >接单</el-button
            >
            <el-button
              type="danger"
              style="width: 50px; text-align: center"
              size="small"
              @click="Transfers(scope.row)"
              >转单</el-button
            >
          </div>
          <div v-else-if="radio1 == 'REPAIR'">
            <el-button
              type="primary"
              icon="el-icon-edit"
              style="width: 50px; text-align: center"
              size="small"
              @click="comSubmit(scope.row)"
              >完成</el-button
            >
            <el-button
              type="danger"
              style="width: 70px; text-align: center"
              size="small"
              @click="execeptSubmit(scope.row)"
              >上传异常</el-button
            >
          </div>
          <div v-else>
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="arrge(scope.row)"
              >修改状态</el-button
            >
          </div>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @current-change="handlePageChange"
      v-model:current-page="currentPage"
      :page-sizes="[10, 20, 30, 50]"
      :size="pageName.pageSize"
      :total="tableData.length"
      layout="total,sizes, prev, pager, next"
    >
      <template v-slot:total>
        <span>总页数: {{ total }}</span>
      </template>
    </el-pagination>
    <el-dialog
      v-model="dialogVisible"
      title="订单状态"
      width="500"
      :before-close="handleClose"
    >
      <div style="height: 150px">
        <span>订单状态：</span>
        <el-select
          v-model="value"
          placeholder="Select"
          size="large"
          style="width: 240px"
        >
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="changeStatus"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog
      v-model="dialogVisible1"
      title="派单处理"
      width="500"
      :before-close="handleClose"
    >
      <div>
        <span>请选择维修人员:</span>
        <el-select
          v-model="dispatchForm.appointeeId"
          placeholder="请选择维修人员"
          size="large"
          style="width: 240px"
          @change="getCollaborators"
        >
          <el-option
            v-for="item in Peroptions"
            :key="item.userId"
            :label="item.nickName"
            :value="item.userId"
          />
        </el-select>
      </div>
      <div style="margin-top: 20px">
        <span>请选择协同人员:</span>
        <el-select
          v-model="tempCollpeo"
          multiple
          placeholder="请选择协同人员（可多选）"
          size="large"
          style="width: 240px"
        >
          <el-option
            v-for="item in Collaborators"
            :key="item.userId"
            :label="item.nickName"
            :value="item.userId"
          />
        </el-select>
      </div>
      <span style="margin-top: 20px">请输入你的备注:</span>
      <div style="margin-top: -10px; margin-left: 115px; margin-bottom: 20px">
        <el-input
          v-model="dispatchForm.dispatchNote"
          maxlength="30"
          style="width: 240px"
          placeholder="最多30字"
          show-word-limit
          type="textarea"
        />
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible1 = false">取消</el-button>
          <el-button type="primary" @click="godispath"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog v-model="TranSferVissable" title="转单处理" width="500">
      <el-form
        :model="TransfersForm"
        label-width="auto"
        style="max-width: 600px"
      >
        <el-form-item label="转单编号">
          <span>{{ TransfersForm.id }}</span>
        </el-form-item>
        <el-form-item>
          <span>请选择接单人员</span>
          <el-select
            v-model="TransfersForm.receiverName"
            placeholder="Select"
            size="large"
            style="width: 240px"
          >
            <el-option
              v-for="item in Peroptions"
              :key="item.userId"
              :label="item.label"
              :value="item.nickName"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <span>备注</span>
          <el-input
            v-model="TransfersForm.transferContent"
            maxlength="30"
            style="width: 240px"
            placeholder="请输入转单描述"
            show-word-limit
            type="textarea"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="TranSferVissable = false">取消</el-button>
          <el-popconfirm
            confirm-button-text="确定"
            cancel-button-text="取消"
            :icon="InfoFilled"
            icon-color="#626AEF"
            title="您确定要转单吗?"
            @confirm="tranSfrom"
          >
            <template #reference>
              <el-button>确定</el-button>
            </template>
          </el-popconfirm>
        </div>
      </template>
    </el-dialog>
    <!-- 完成订单上报 -->
    <el-dialog v-model="comFormDiavissable" title="完成订单上报" width="500">
      <el-form
        :model="completeForm"
        label-width="auto"
        style="max-width: 600px"
      >
        <el-form-item label="订单编号" style="margin-top: 10px">
          <el-input disabled v-model="completeForm.id" />
        </el-form-item>
        <el-form-item label="使用物料">
          <el-select
            v-model="equipListValue"
            placeholder="请选择使用的物料"
            multiple
            @change="changeEquiplist"
          >
            <el-option
              v-for="item in equipList"
              :key="item.id"
              :label="item.partName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="使用物料数量">
          <div v-for="item in foundItems" :key="item.Id">
            {{ item.partName }}
            <el-input-number
              v-model="item.number"
              :min="1"
              :max="item.partQty"
            />
            剩余数量：{{ item.partQty }}
          </div>
        </el-form-item>
        <el-form-item label="上传图片">
          <el-upload
            ref="uploadRef"
            class="upload-demo"
            multiple
            :auto-upload="false"
            :http-request="uploadFile"
            :on-change="handleChange"
            :before-upload="beforeUpload"
          >
            <template #trigger>
              <el-button type="primary">选择图片</el-button>
            </template>

            <el-button
              class="ml-3"
              type="success"
              @click="upload(index.params)"
            >
              上传图片
            </el-button>

            <template #tip>
              <div class="el-upload__tip">
                jpg/png files with a size less than 500kb
              </div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item label="完成时间">
          <div class="block">
            <el-date-picker
              v-model="completeForm.maintenanceTime"
              type="date"
              placeholder="选择时间"
              :size="size"
            />
          </div>
        </el-form-item>
        <el-form-item label="维修描述">
          <el-input
            v-model="completeForm.maintenanceDescription"
            type="textarea"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="comFormDiavissable = false">取消</el-button>
          <el-button type="primary" @click="comSubmitSure"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog v-model="execeptDiavissable" title="异常订单上报">
      <el-form :model="execept">
        <el-form-item label="订单编号"
          ><el-input v-model="execept.id" disabled></el-input
        ></el-form-item>
        <el-form-item label="异常原因">
          <el-input type="textarea" v-model="execept.exceptionCause"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="comFormDiavissable = false">取消</el-button>
          <el-button type="primary" @click="exeSubmitSure"> 上传 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import {
  getRepairList,
  orderView,
  dispatchOrder,
  receiveOrder,
  getReceiveOrder,
  TransfersOrder,
  getEquipList,
  postPicture,
  completeSubmit,
  exceptionSubmit
} from '@/api/repairList'
import { getRepairPeo } from '@/api/getList'

import { ref, computed, onMounted } from 'vue'
import { useUserStore } from '@/stores/user'
import { useTitleStore } from '@/stores/titleNav'
import { ElMessage } from 'element-plus'
import ConfirmDialog from '@/components/ConfirmDialog.vue'

const confirmDialog = ref(null)

const openConfirmDialog = () => {
  confirmDialog.value.open()
}

// import { ElMessage, valueEquals } from 'element-plus'
const tableLayout = ref('fixed')
const userStore = useUserStore()
const titleStore = useTitleStore()
const tableData = ref([])
const value1 = ref()
const radio1 = ref('CREATE')
const index = ref({
  index: '/ordercenter/orderlist',
  title: '订单列表'
})
// const equipname = ref('')s
const pageName = ref({
  pageNum: 1,
  pageSize: 10,
  sort: 1,
  repairId: '',
  contactName: '',
  acceptorName: '',
  startTime: '',
  endTime: ''
})
const currentPage = ref(1)
const pageSize = ref(10)
const dialogVisible = ref(false)

const getList1 = () => {
  // pageName.value.startTime = value1.value[0]
  // pageName.value.endTime = value1.value[1]
  // console.log(pageName.value)
  pageName.value.startTime = value1.value[0]
  pageName.value.endTime = value1.value[1]

  // 格式化日期时间字符串
  const formatDate = (dateString) => {
    const date = new Date(dateString)
    const formattedDate = date.toLocaleString('en-US', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit',
      hour12: false
    })
    return formattedDate
  }

  // 应用格式化函数
  const startTimeFormatted = formatDate(pageName.value.startTime)
  const endTimeFormatted = formatDate(pageName.value.endTime)

  // 将格式化后的日期赋值给对应的属性
  const formatDate1 = (dateString) => {
    // 使用 toISOString 方法格式化日期为 ISO 8601 格式，然后进行进一步处理
    const isoDate = new Date(dateString).toISOString()
    const [datePart, timePart] = isoDate.split('T')
    const [year, month, day] = datePart.split('-')
    const [hour, minute, second] = timePart.split(':')

    // 拼接成所需的格式
    return `${year}-${month.padStart(2, '0')}-${day.padStart(2, '0')} ${hour}:${minute}:${second}`
  }
  const removeMicrosecondsAndTimezone = (dateString) => {
    // 使用 split 方法分割字符串
    const [datePart, timePart] = dateString.split('.')
    const [timePartWithoutMicroseconds, timezone] = timePart.split('000Z')

    // 拼接成所需的格式
    return `${datePart}${timePartWithoutMicroseconds}${timezone}`
  }
  const startTimeFormatted1 = formatDate1(startTimeFormatted)
  const endTimeFormatted1 = formatDate1(endTimeFormatted)
  pageName.value.startTime = removeMicrosecondsAndTimezone(startTimeFormatted1)
  pageName.value.endTime = removeMicrosecondsAndTimezone(endTimeFormatted1)
  // console.log(pageName.value)

  getList()
}

const pagedTableData = computed(() => {
  return tableData.value.slice(
    (currentPage.value - 1) * pageSize.value,
    currentPage.value * pageSize.value
  )
})

const handlePageChange = (newPage) => {
  currentPage.value = newPage
  // 可以在这里添加其他逻辑
}
const statusForm = ref({
  id: '',
  repairStatus: ''
})
// 派单处理
const dialogVisible1 = ref(false)
const Dispatch = async (row) => {
  dialogVisible1.value = true
  dispatchForm.value.id = row.id
}
const godispath = async () => {
  dispatchForm.value.appointeeName = Peroptions.value.find((item) => {
    return item.nickName && item.userId == dispatchForm.value.appointeeId
  }).nickName
  dispatchForm.value.collaboratorList = Peroptions.value.filter((option) =>
    tempCollpeo.value.includes(option.userId)
  )
  const res = await dispatchOrder(dispatchForm.value)
  if (res.code == 200) {
    ElMessage({
      message: '派单成功',
      type: 'success'
    })
    getList()
    dialogVisible1.value = false
  } else {
    ElMessage({
      message: '未知错误，请联系管理员',
      type: 'warning'
    })
  }
}
// const arrge = async (row) => {//修改状态栏
//   console.log(row)
//   dialogVisible.value = true
//   statusForm.value.id = row.id
//   value.value = row.repairStatus
// }
const aggree = (row) => {
  statusForm.value.id = row.id
  statusForm.value.repairStatus = 'APPROVED'
  changeStatus()
}
const rejuct = (row) => {
  statusForm.value.id = row.id
  statusForm.value.repairStatus = 'REJECTED'
  changeStatus()
}
const changeStatus = async () => {
  const res = await orderView(statusForm.value)
  if (res.code == 200) {
    ElMessage({
      message: '审核成功',
      type: 'success'
    })
    getList()
  } else {
    ElMessage({
      message: '未知错误，请联系管理员',
      type: 'error'
    })
  }
}
const headers = ref([])
//处理跳转带回来的token
const getList = async () => {
  if (window.location.search.includes('token=')) {
    const params = new URLSearchParams(window.location.search)
    const receivedToken = params.get('token')
    userStore.updateUserInfo({ token: receivedToken })
  }
  const res = await getRepairList(pageName.value)
  console.log(res)
  const res1 = await getReceiveOrder()
  console.log(userStore.userInfo, res1)
  if (userStore.userInfo.info.roles[0].roleName == '超级管理员') {
    tableData.value = res.data.pageInfo.list.filter(
      (item) => item.repairStatus === radio1.value
    )
    headers.value = res.data.header
    console.log(headers.value)
    tableData.value = tableData.value.map((item) => {
      // 提取equipList数组中的name值
      const names = item.equipmentList.map((device) => device.name).join(', ')
      // 返回一个新对象，包含拼接后的设备名称和其他属性
      return { ...item, equipmentList: names }
    })
  } else {
    tableData.value = res1.data.list.filter(
      (item) => item.repairStatus === radio1.value
    )
    tableData.value = tableData.value.map((item) => {
      // 提取equipList数组中的name值
      const names = item.equipmentList.map((device) => device.name).join(', ')
      // 返回一个新对象，包含拼接后的设备名称和其他属性
      return { ...item, equipmentList: names }
    })
  }
}

const value = ref('')

const options = ref([
  {
    value: 'CREATE',
    label: '未审核'
  },
  {
    value: 'APPROVED',
    label: '审核通过'
  },
  {
    value: 'REJECTED',
    label: '未通过审核'
  },
  {
    value: 'PENDING',
    label: '待受理订单'
  }
])
const tempCollpeo = ref([])
const dispatchForm = ref({
  id: '',
  dispatchNote: '',
  appointeeId: '', // 指派人员id
  appointeeName: '', // 指派人员姓名
  collaboratorList: [] // 协作人员（多选
})
const getPerson = async () => {
  //获取维修工身份字段
  const res = await getRepairPeo()
  Peroptions.value = res.data.map((user) => ({
    userId: user.userId,
    nickName: user.nickName
  }))
}
const Peroptions = ref([])
const Collaborators = ref([])
const getCollaborators = () => {
  //动态获取协作人员信息
  Collaborators.value = Peroptions.value.filter((item) => {
    return item.userId != dispatchForm.value.appointeeId
  })
}
const receiveForm = ref({
  id: ''
})
const PutreciveOrder = async (row) => {
  receiveForm.value.id = row.id
  const res = await receiveOrder(receiveForm.value)
  if (res.code == 200) {
    ElMessage({
      message: '接单成功',
      type: 'success'
    })
    getList()
  }
}
const TransfersForm = ref({
  id: '',
  receiverId: '',
  receiverName: '',
  transferContent: ''
})
const TranSferVissable = ref(false)
const Transfers = async (row) => {
  TransfersForm.value.id = row.id
  TranSferVissable.value = true
}
// 转单处理
const tranSfrom = async () => {
  const matchedUser = Peroptions.value.find(
    (item) => item.nickName === TransfersForm.value.receiverName
  )
  if (matchedUser) {
    TransfersForm.value.receiverId = matchedUser.userId
  } else {
    TransfersForm.value.receiverId = '' // 或者其他默认值
  }
  const res = await TransfersOrder(TransfersForm.value)
  if (res.code == 200) {
    ElMessage({
      message: '转单成功',
      type: 'success'
    })
    getList()
    // 对表单进行初始化
    TranSferVissable.value = false
    TransfersForm.value.id = ''
    TransfersForm.value.receiverId = ''
    TransfersForm.value.receiverName = ''
    TransfersForm.value.transferContent = ''
  }
}
const equipList = ref([])
const comFormDiavissable = ref(false)
const getEquip = async () => {
  const res = await getEquipList()
  if (res.code == 200) {
    equipList.value = res.data.list
    equipList.value.map((item) => {
      item.number = 1
    })
    console.log(equipList.value)
    comFormDiavissable.value = true
  } else {
    ElMessage({
      message: '未知错误，请联系管理员',
      type: 'danger'
    })
  }
}
const comSubmit = (index) => {
  console.log(index)
  completeForm.value.id = index.id
  getEquip()
}
const foundItems = ref([])
const equipListValue = ref([])
const changeEquiplist = () => {
  console.log(equipList.value)
  foundItems.value = equipList.value.filter((item) => {
    return equipListValue.value.includes(item.id)
  })
}
const completeForm = ref({
  id: '',
  maintenanceTime: '',
  maintenanceDescription: '',
  pictureList: [],
  partList: []
})
// 图片上传
const uploadRef = ref(null)
const uploadFiles = ref([])
const filesLength = ref(0)
const upload = () => {
  //上传图片
  uploadRef.value.submit()
}
const handleChange = (file, fileList) => {
  filesLength.value = fileList.length
  console.log(filesLength.value)
}
const uploadFile = async (param) => {
  // 等待所有文件被选中后，再进行上传
  uploadFiles.value.push(param.file)
  console.log(uploadFiles.value.length, filesLength.value)
  if (uploadFiles.value.length === filesLength.value) {
    let fd = new FormData()
    // 将全部文件添加至FormData中
    uploadFiles.value.forEach((file) => {
      fd.append('file', file)
    })
    try {
      const res = await postPicture(fd)
      console.log(res)
      completeForm.value.pictureList = res.data
    } catch (error) {
      console.error('Upload failed:', error)
    }
  }
}
// 提交完成订单
const comSubmitSure = async () => {
  completeForm.value.partList = foundItems.value.map((item) => {
    // eslint-disable-next-line no-unused-vars
    const { partQty, ...rest } = item
    return rest
  })
  const date = new Date(completeForm.value.maintenanceTime.toString())

  const year = date.getFullYear()
  const month = (date.getMonth() + 1).toString().padStart(2, '0') // 月份是从0开始的，所以需要+1
  const day = date.getDate().toString().padStart(2, '0')

  const formattedDate = `${year}-${month}-${day}`
  completeForm.value.maintenanceTime = formattedDate
  const res = await completeSubmit(completeForm.value)
  if (res.code == 200) {
    ElMessage({
      message: '修改成功',
      type: 'success'
    })
    completeForm.value.maintenanceTime = ''
    comFormDiavissable.value = false
  } else {
    ElMessage({
      messsage: '未知错误，请联系管理员',
      type: 'danger'
    })
  }
}
const execept = ref({
  id: '',
  exceptionCause: '' //异常原因
})
const execeptDiavissable = ref(false)
const execeptSubmit = (row) => {
  execept.value.id = row.id
  execeptDiavissable.value = true
}
const exeSubmitSure = async () => {
  const res = await exceptionSubmit(execept.value)
  if (res.code == 200) {
    ElMessage({
      message: '上传成功',
      type: 'success'
    })
    execeptDiavissable.value = false
  } else {
    ElMessage({
      message: '未知异常',
      type: 'danger'
    })
  }
}

onMounted(() => {
  titleStore.updataTitInfo(index)
  getList()
  getPerson() //获取维修工信息
  PutreciveOrder()
})
</script>
<style scoped lang="less"></style>
